
package com.youease.chris.animate {
	import com.youease.chris.event.AnimateEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	
	/**
	 * Animation
	 *
	 * @author chris
	 *
	 * Dec 19, 2012
	 */
	public class Animation extends Sprite {
		private var sources:Array;
		public var source:Bitmap;
		public var currentFrame:int = 0;
		public var frameTime:Number = 0;
		public var fps:int = 24;
		public var currentCount:int = 0;
		public var count:int = -1;
		
		public function Animation(sources:Array=null,fps:int=24,count:int=1)
		{
			super();
			source = new Bitmap();
			this.addChild(source);
			this.sources = sources;
			this.fps = fps;
			this.count = count;
			if(this.sources) {
				if(this.sources.length>1) {
					this.source.bitmapData = this.sources[0];
				}else {
					throw new Error("动画帧数不能少于2");
				}
			}
		}
		
		/**
		 * @param dt两帧间隔(秒)
		 * 
		 */ 
		public function enterFrame(dt:Number):void
		{
			frameTime += dt;
			var changeFrame:Boolean = false;
			while (frameTime > 1/fps)
			{
				frameTime -= 1/fps;
				currentFrame = (currentFrame + 1) % this.sources.length;
				changeFrame = true;
			}
			if(changeFrame) {
				source.bitmapData = this.sources[currentFrame];
				if(currentFrame == this.sources.length-1) {
					if(++currentCount == count) {
						this.dispatchEvent(new AnimateEvent(AnimateEvent.ANIMATE_COMPLETE));
					}
				}
			}
		}
		
		public function set frames(sources:Array):void {
			if(!sources || sources.length<2) {
				throw new Error("动画帧数不能少于2");
			}else {
				this.sources = sources;
				this.source.bitmapData = this.sources[0];
			}
		}
		
		public function get frames():Array {
			return this.sources;
		}
		
	}
}